<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>订单管理</title>
  <!-- 引入 Vue.js -->
  <script src="/js/vue.js"></script>
  <!-- 引入 ElementUI CSS -->
  <link type="text/css" rel="stylesheet" href="/css/index.css">
  <!-- 引入 ElementUI JS -->
  <script src="/js/index.js"></script>
  <!-- 引入 axios -->
  <script src="/js/axios.min.js"></script>
  <script src="/js/vue-qriously.js"></script>
</head>
<body>
<div id="app">
  <!-- 卡片包裹 -->
  <el-card shadow="hover" style="margin: 10px;">
    <!-- 搜索区域 -->
    <el-row :gutter="10" style="margin-bottom: 10px;">
      <el-col :span="4">
        <el-input size="mini" v-model="searchForm.orderQpname" placeholder="请输入取票人名字"></el-input>
      </el-col>
      <el-col :span="4">
        <el-input size="mini" v-model="searchForm.scenicName" placeholder="请输入景区名称"></el-input>
      </el-col>
      <el-col :span="4">
      </el-col>
      <el-col :span="4">
        <el-select size="mini" v-model="searchForm.orderState" placeholder="选择订单状态">
          <el-option label="待付款" value="11"></el-option>
          <el-option label="已付款" value="12"></el-option>
          <el-option label="已取票" value="13"></el-option>
          <el-option label="待审核" value="14"></el-option>
          <el-option label="已退款" value="15"></el-option>
          <el-option label="待付款退单结束" value="20"></el-option>
          <el-option label="付款超时结束" value="21"></el-option>
          <el-option label="预订成功退单结束" value="22"></el-option>
          <el-option label="退款审核不通过结束" value="23"></el-option>
          <el-option label="退款完成结束" value="24"></el-option>
          <el-option label="取票超时结束" value="25"></el-option>
          <el-option label="退票结束" value="26"></el-option>
          <el-option label="点评超时结束" value="27"></el-option>
          <el-option label="点评完成结束" value="28"></el-option>
        </el-select>
      </el-col>
      <el-col :span="8">
        <el-button size="mini" icon="el-icon-search" type="primary" @click="search">搜索</el-button>
        <el-button size="mini" type="success" @click="handleAdd">添加订单</el-button>
      </el-col>
    </el-row>

    <!-- 订单列表（已删除订单项展示列） -->
    <el-table :data="tableData" border stripe style="width: 100%">
      <el-table-column prop="orderNo" label="订单号" width="120"></el-table-column>
      <el-table-column label="游玩日期" width="120">
        <template slot-scope="scope">
          {{ formatDate(scope.row.orderYwrq) }}
        </template>
      </el-table-column>
      <el-table-column prop="orderPtype" label="支付方式" width="100">
        <template slot-scope="scope">
          {{ scope.row.orderPtype === '1' ? '景区支付' : '在线支付' }}
        </template>
      </el-table-column>
      <el-table-column prop="orderCount" label="总票数" width="80"></el-table-column>
      <el-table-column prop="orderTprice" label="总票价" width="100"></el-table-column>
      <el-table-column prop="orderQpname" label="取票人名字" width="100"></el-table-column>
      <el-table-column prop="orderQprsj" label="取票人手机" width="120"></el-table-column>
      <el-table-column prop="orderState" label="订单状态" width="140">
        <template slot-scope="scope">
          <el-tag :type="getStateTagType(scope.row.orderState)">{{ getStateText(scope.row.orderState) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="400">
        <template slot-scope="scope">
          <!-- 新增查看详情按钮 -->
          <el-button size="mini" type="info" @click="viewOrderDetail(scope.row)">
            查看详情
          </el-button>
          <!-- 当订单状态为待退款(15)时，只显示查看详情按钮 -->
          <template v-if="scope.row.orderState !== '15'">
            <!-- 原有“编辑”“删除”按钮 -->
            <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>

          </template>
          <!-- 当订单状态为已取票(13)时，不显示退款按钮 -->
          <template v-else-if="scope.row.orderState === '13'">
            <el-button size="mini" type="info" disabled>已取票</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            style="margin-top: 10px; text-align: right;">
    </el-pagination>
  </el-card>

  <!-- 支付弹窗（已删除订单项表格） -->
  <el-dialog
          title="订单支付"
          :visible.sync="showPayment"
          width="35%">
    <div v-if="currentPayingOrder">
      <div style="margin-bottom:10px;">支付金额：￥{{ currentPayingOrder.orderTprice }}</div>
      <div style="margin-bottom:10px;">订单号：{{ currentPayingOrder.orderNo }}</div>
      <div style="margin-bottom:10px;">支付状态：{{ paystatus }}</div>
      <qriously v-if="code_url" :value="code_url" :size="260"/>
    </div>
  </el-dialog>
  <!-- 订单详情弹窗 -->
  <el-dialog
          title="订单详情"
          :visible.sync="showOrderDetailDialog"
          width="60%">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="订单号">{{ orderDetail.orderNo || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ formatDateTime(orderDetail.orderTime) || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="支付方式">
            {{ orderDetail.orderPtype === '1' ? '景区支付' : '在线支付' }}
          </el-descriptions-item>
          <el-descriptions-item label="总票数">{{ orderDetail.orderCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="总金额">￥{{ orderDetail.orderTprice || 0 }}</el-descriptions-item>
        </el-descriptions>
      </el-col>

      <el-col :span="8">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="取票人姓名">{{ orderDetail.orderQpname || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="取票人手机">{{ orderDetail.orderQprsj || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStateTagType(orderDetail.orderState)">
              {{ getStateText(orderDetail.orderState) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-col>

      <el-col :span="8">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="支付时间">{{ orderDetail.payTime ? formatDateTime(orderDetail.payTime) : (orderDetail.orderState === '12' ? '已支付但未记录时间' : '未支付') }}</el-descriptions-item> <!-- 新增支付时间显示 -->
          <el-descriptions-item label="取票时间">{{ orderDetail.qpTime || '未取票' }}</el-descriptions-item>
          <el-descriptions-item label="退款状态">
            <template v-if="refundInfo">
              <el-tag :type="getRefundTagType(refundInfo.refundResult)">
                {{ getRefundStatusText(refundInfo.refundResult) }}
              </el-tag>
            </template>
            <template v-else>
              <el-tag type="default">未申请退款</el-tag>
            </template>
          </el-descriptions-item>
        </el-descriptions>
      </el-col>
    </el-row>

    

    <el-table :data="orderDetail.orderItemList || []"border stripe style="width: 100%">
      <el-table-column label="景区名称" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.ticket && scope.row.ticket.scenic && scope.row.ticket.scenic.scenicName">
            {{scope.row.ticket.scenic.scenicName }}
          </span>
          <span v-else-if="scope.row.ticket && scope.row.ticket.scenicName">
            {{scope.row.ticket.scenicName }}
          </span>
          <span v-else-if="scope.row.scenic && scope.row.scenic.scenicName">
            {{scope.row.scenic.scenicName }}
          </span>
          <span v-else>
            {{scope.row.scenicName || '未知景区' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="ticket.ticketName" label="门票名称" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.ticket">
            {{scope.row.ticket.ticketName }}
          </span>
          <span v-else>
            {{scope.row.ticketName || '未知门票' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="unitPrice" label="单价" width="100">
        <template slot-scope="scope">￥{{ scope.row.unitPrice }}</template>
      </el-table-column>
      <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
      <el-table-column label="小计" width="100">
        <template slot-scope="scope">￥{{ (scope.row.unitPrice * scope.row.quantity).toFixed(2) }}</template>
      </el-table-column>
      <el-table-column prop="ticket.ticketDesc" label="门票说明">
        <template slot-scope="scope">
          <span v-if="scope.row.ticket">
            {{scope.row.ticket.ticketDesc }}
          </span>
          <span v-else>
            {{scope.row.ticketDesc || '无说明' }}
          </span>
        </template>
      </el-table-column>
    </el-table>

    <span slot="footer" class="dialog-footer">
    <el-button @click="showOrderDetailDialog = false">关闭</el-button>
  </span>
  </el-dialog>

  <!-- 退款弹窗（保留原有功能） -->
  <el-dialog
          title="申请退款"
          :visible.sync="showRefund"
          width="35%">
    <el-form :model="refundForm" :rules="refundRules" ref="refundForm" label-width="120px">
      <!-- 订单号（只读，回显当前订单号） -->
      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="refundForm.orderNo" disabled placeholder="订单号自动填充"></el-input>
      </el-form-item>
      <!-- 退款金额（必填，默认等于订单总金额，支持部分退款） -->
      <el-form-item label="退款金额（元）" prop="refundIje">
        <el-input
                v-model.number="refundForm.refundIje"
                type="number"
                :step="0.01"
                :min="0.01"
                :max="refundMaxAmount"
                placeholder="请输入退款金额">
          <template slot="append">元</template>
        </el-input>
        <div style="color:#666; font-size:12px; margin-top:5px;">
          订单总金额：￥{{ refundMaxAmount }}，支持部分退款
        </div>
      </el-form-item>
      <!-- 退款原因（非必填，可选填） -->
      <el-form-item label="退款原因" prop="refundReason">
        <el-input
                v-model="refundForm.refundReason"
                type="textarea"
                rows="3"
                placeholder="请输入退款原因（可选）"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="showRefund = false">取消</el-button>
      <el-button type="primary" @click="submitRefund">提交退款申请</el-button>
    </div>
  </el-dialog>

  <!-- 新增/编辑订单弹窗（保留订单项录入功能，用于订单创建） -->
  <el-dialog :title="title" :visible.sync="dialogFormVisible" width="70%">
    <el-form :model="form" :rules="rules" ref="form" label-width="120px">
      <!-- 订单号：新增时禁用（自动生成），编辑时禁用（不可修改） -->
      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="form.orderNo" autocomplete="off" :disabled="true"></el-input>
      </el-form-item>

      <el-form-item label="游玩日期" prop="orderYwrq">
        <el-date-picker v-model="form.orderYwrq" type="date" placeholder="选择游玩日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="支付方式" prop="orderPtype">
        <el-radio-group v-model="form.orderPtype">
          <el-radio :label="'1'">景区支付</el-radio>
          <el-radio :label="'2'">在线支付</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 订单项列表（保留录入功能，用于计算总金额和提交订单） -->
      <el-form-item label="订单项">
        <el-table :data="form.orderItems" border style="width: 100%; margin-bottom: 10px;">
          <el-table-column label="景区" width="150">
            <template slot-scope="scope">
              <el-select
                      v-model="scope.row.scenicId"
                      placeholder="请选择景区"
                      @change="handleItemScenicChange(scope.row, scope.$index)">
                <el-option
                        v-for="scenic in scenicList"
                        :key="scenic.scenicId"
                        :label="scenic.scenicName"
                        :value="scenic.scenicId">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="门票" width="180">
            <template slot-scope="scope">
              <el-select
                      v-model="scope.row.ticketId"
                      placeholder="请选择门票"
                      @change="handleItemTicketChange(scope.row, scope.$index)">
                <el-option
                        v-for="ticket in getTicketListByScenicId(scope.row.scenicId)"
                        :key="ticket.ticketId"
                        :label="ticket.ticketName"
                        :value="ticket.ticketId">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="单价" width="180">
            <template slot-scope="scope">
              <el-input
                      v-model.number="scope.row.itemPrice"
                      type="number"
                      :step="0.01"
                      :min="0.01"
                      @change="calculateItemTotal(scope.row)">
                <template slot="append">元</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="100">
            <template slot-scope="scope">
              <el-input-number
                      v-model.number="scope.row.itemCount"
                      :min="1"
                      :max="100"
                      :step="1"
                      controls-position="right"
                      @change="calculateItemTotal(scope.row)">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="小计" width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.itemTotalPrice || 0 }} 元</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button
                      type="danger"
                      size="mini"
                      @click="removeOrderItem(scope.$index)"
                      :disabled="form.orderItems.length <= 1">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" size="mini" @click="addOrderItem">+ 添加订单项</el-button>
        <div style="margin-top: 10px; text-align: right;">
          <strong>订单总金额：{{ calculateTotalPrice() }} 元</strong>
        </div>
      </el-form-item>

      <el-form-item label="游客信息">
        <!-- 遍历每一位游客 -->
        <div v-for="(v,index) in form.visitors" :key="index" style="margin-bottom:8px; display:flex; align-items:center;">
          <el-input
                  v-model="v.visitorName"
                  placeholder="游客姓名"
                  style="width:120px;margin-right:8px;">
          </el-input>
          <el-input
                  v-model="v.visitorPhone"
                  placeholder="游客手机号"
                  style="width:150px;margin-right:8px;">
          </el-input>
          <el-button type="danger" size="mini" @click="form.visitors.splice(index,1)">删除</el-button>
        </div>
        <el-button type="primary" size="mini" @click="addVisitor">+ 添加游客</el-button>
      </el-form-item>
      <el-form-item label="取票人名字" prop="orderQpname">
        <el-input v-model="form.orderQpname" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="取票人手机" prop="orderQprsj">
        <el-input v-model="form.orderQprsj" autocomplete="off" placeholder="请输入11位手机号"></el-input>
      </el-form-item>
      <el-form-item label="订单状态" prop="orderState">
        <el-select v-model="form.orderState" placeholder="选择订单状态">
          <el-option label="待付款" value="11"></el-option>
          <el-option label="已付款" value="12"></el-option>
          <el-option label="已取票" value="13"></el-option>
          <el-option label="待审核" value="14"></el-option>
          <el-option label="待退款" value="15"></el-option>
          <el-option label="待付款退单结束" value="20"></el-option>
          <el-option label="付款超时结束" value="21"></el-option>
          <el-option label="预订成功退单结束" value="22"></el-option>
          <el-option label="退款审核不通过结束" value="23"></el-option>
          <el-option label="退款完成结束" value="24"></el-option>
          <el-option label="取票超时结束" value="25"></el-option>
          <el-option label="退票结束" value="26"></el-option>
          <el-option label="点评超时结束" value="27"></el-option>
          <el-option label="点评完成结束" value="28"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button @click="resetForm('form')">重置</el-button>
      <el-button type="primary" @click="submitForm('form')">确 定</el-button>
    </div>
  </el-dialog>
</div>

<script>
  // 日期格式化函数
  function formatDate(date) {
    if (!date) return '';
    const d = new Date(date);
    let month = '' + (d.getMonth() + 1);
    let day = '' + d.getDate();
    const year = d.getFullYear();
    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;
    return [year, month, day].join('-');
  }

  // 日期时间格式化函数（新增）
  function formatDateTime(dateTime) {
    if (!dateTime) return '';
    try {
      // 创建Date对象
      const date = new Date(dateTime);

      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return dateTime; // 如果无效，返回原始值
      }

      // 获取年月日
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');

      // 获取时分秒
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      // 返回格式化后的字符串
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    } catch (error) {
      console.error('时间格式化错误:', error);
      return dateTime; // 出错时返回原始值
    }
  }

  // 生成唯一订单号（规则：YYYYMMDDHHMMSS + 6位随机数）
  function generateOrderNo() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const random = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
    return `${year}${month}${day}${hours}${minutes}${seconds}${random}`;
  }

  new Vue({
    el: '#app',
    data() {
      return {
        showOrderDetailDialog: false,  // 控制订单详情弹窗的显示
        orderDetail: {},               // 存储订单详情
        refundInfo: null,
        tableData: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
        searchForm: {
          orderId: '',
          orderNo: '',
          orderQpname: '',
          orderYwrq: '',
          orderState: '',
          scenicName: '',
          ticketName: ''
        },
        dialogFormVisible: false,
        title: '添加订单',
        isEdit: false,
        // 景区/门票下拉列表数据
        scenicList: [],
        ticketList: [],
        form: {
          orderId: '',
          visitorId: 1, // 临时固定值，后续从登录态获取
          orderNo: '', // 新增时自动生成，编辑时回显
          orderYwrq: '',
          orderPtype: '',
          orderTprice: 0, // 订单总金额
          orderCount: 0, // 订单总数量
          orderQpname: '',
          orderQprsj: '',
          orderState: '',
          visitors: [],
          orderItems: [] // 订单项列表（保留，用于录入和提交）
        },
        rules: {
          orderNo: [{required: true, message: '订单号不可为空', trigger: 'blur'}],
          orderYwrq: [{required: true, message: '请选择游玩日期', trigger: 'change'}],
          orderPtype: [{required: true, message: '请选择支付方式', trigger: 'change'}],
          orderQpname: [
            {required: true, message: '请输入取票人名字', trigger: 'blur'},
            {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
          ],
          orderQprsj: [
            {required: true, message: '请输入取票人手机', trigger: 'blur'},
            {pattern: /^1\d{10}$/, message: '请输入正确的11位手机号', trigger: 'blur'}
          ],
          orderState: [{required: true, message: '请选择订单状态', trigger: 'change'}]
        },
        // 支付相关变量
        showPayment: false,
        code_url: "",
        paystatus: "",
        timer1: null,
        currentPayingOrder: null,

        // 退款相关变量
        showRefund: false,
        currentRefundingOrder: null,
        refundMaxAmount: 0,
        refundForm: {
          orderNo: '',
          refundIje: null,
          refundReason: ''
        },
        refundRules: {
          orderNo: [{required: true, message: '订单号不可为空', trigger: 'blur'}],
          refundIje: [
            {required: true, message: '请输入退款金额', trigger: 'blur'},
            {type: 'number', min: 0.01, message: '退款金额至少为0.01元', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                if (value > this.refundMaxAmount) {
                  callback(new Error(`退款金额不能超过订单总金额（￥${this.refundMaxAmount}）`));
                } else {
                  callback();
                }
              },
              trigger: 'blur'
            }
          ]
        }
      };
    },
    // 页面加载时加载景区列表
    created() {
      this.searchForm = {};
      this.currentPage = 1;
      this.loadScenicList();
      this.loadData();
    },
    methods: {
      addVisitor() {
        this.form.visitors.push({
          visitorName: '',
          visitorPhone: ''
        });
      },

      // 查看订单详情
      viewOrderDetail(order) {
        // 设置订单详情数据
        this.orderDetail = order;  // 假设 `order` 是传递的订单对象

        // 重置退款信息，避免上次查询的结果残留
        this.refundInfo = null;

        // 只有在订单状态是退款相关状态时才查询退款信息
        const refundRelatedStates = ['15', '23', '24']; // 待退款、退款审核不通过结束、退款完成结束
        if (refundRelatedStates.includes(order.orderState)) {
          this.loadRefundInfoByOrderNo(order.orderNo);  // 加载退款信息
        }
        // 2. 新增：加载支付信息（获取pay_time）
        this.loadPayInfoByOrderNo(order.orderNo);
        this.showOrderDetailDialog = true;  // 显示订单详情弹窗
      },

      // 新增：根据订单号查询支付记录
      loadPayInfoByOrderNo(orderNo) {
        if (!orderNo) return;

        axios.get(`/pay/queryByOrderNo/${orderNo}`)
                .then(res => {
                  if (res.data.code === 200 && res.data.data) {
                    // 将支付时间同步到订单详情中
                    this.orderDetail.payTime = res.data.data.payTime;
                  }
                })
                .catch(error => {
                  console.error('查询支付记录失败：', error);
                });
      },

      // 加载订单的退款信息
      loadRefundInfoByOrderNo(orderNo) {
        if (!orderNo) {
          this.refundInfo = null;
          return;
        }

        axios.post('/refund/queryByPage', {
          pageNo: 1,
          pageSize: 1,
          data: { orderNo: orderNo }
        })
                .then(res => {
                  if (res.data.code === 200) {
                    const refundList = res.data.data.list;
                    // 只有当有退款记录时才设置refundInfo
                    if (refundList && refundList.length > 0) {
                      this.refundInfo = refundList[0];
                    } else {
                      this.refundInfo = null; // 明确设置为null
                    }
                  } else {
                    console.warn('查询退款记录失败：' + res.data.message);
                    this.refundInfo = null; // 查询失败时也设置为null
                  }
                })
                .catch(error => {
                  console.error('查询退款记录出错：', error);
                  this.refundInfo = null; // 出错时设置为null
                });
      },

      // 订单状态标签样式
      getStateTagType(state) {
        const tagMap = {
          '11': 'warning',
          '12': 'success',
          '13': 'info',
          '14': 'warning',
          '15': 'danger',
          '20': 'info',
          '21': 'danger',
          '22': 'info',
          '23': 'danger',
          '24': 'success',
          '25': 'danger',
          '26': 'info',
          '27': 'danger',
          '28': 'success'
        };
        return tagMap[state] || 'default';
      },

      // 退款状态标签样式
      getRefundTagType(result) {
        const tagMap = {
          '0': 'warning',  // 未完成（处理中）
          '1': 'success',  // 已退款（成功）
          '2': 'danger'    // 已驳回（失败）
        };
        return tagMap[result] || 'default';
      },
      
      // 退款状态文本
      getRefundStatusText(result) {
        const textMap = {
          '0': '未完成',
          '1': '已退款',
          '2': '已驳回'
        };
        return textMap[result] || '未知状态';
      },

      // 订单项相关方法（保留，用于录入和提交）
      addOrderItem() {
        this.form.orderItems.push({
          itemId: null, // 编辑时会有值
          scenicId: null,
          ticketId: null,
          itemPrice: null,
          itemCount: 1,
          itemTotalPrice: null
        });
      },

      removeOrderItem(index) {
        this.form.orderItems.splice(index, 1);
        this.calculateTotalPrice();
      },

      handleItemScenicChange(item, index) {
        // 重置门票选择
        item.ticketId = null;
        item.itemPrice = null;
        item.itemTotalPrice = null;
      },

      handleItemTicketChange(item, index) {
        if (item.ticketId) {
          // 查找门票价格并设置
          const ticket = this.ticketList.find(t => t.ticketId === item.ticketId);
          if (ticket) {
            item.itemPrice = ticket.ticketPrice;
            this.calculateItemTotal(item);
          }
        }
      },

      calculateItemTotal(item) {
        if (item.itemPrice && item.itemCount) {
          item.itemTotalPrice = (item.itemPrice * item.itemCount).toFixed(2);
          this.calculateTotalPrice();
        }
      },

      calculateTotalPrice() {
        let totalPrice = 0;
        let totalCount = 0;

        this.form.orderItems.forEach(item => {
          if (item.itemTotalPrice) {
            totalPrice += parseFloat(item.itemTotalPrice);
          }
          if (item.itemCount) {
            totalCount += parseInt(item.itemCount);
          }
        });

        this.form.orderTprice = totalPrice.toFixed(2);
        this.form.orderCount = totalCount;
        return this.form.orderTprice;
      },

      getTicketListByScenicId(scenicId) {
        if (!scenicId) return [];
        return this.ticketList.filter(ticket => ticket.scenicId === scenicId);
      },

      // 订单状态标签样式映射
      getStateTagType(state) {
        const tagMap = {
          '11': 'warning',
          '12': 'success',
          '13': 'info',
          '14': 'warning',
          '15': 'danger',
          '20': 'info',
          '21': 'danger',
          '22': 'info',
          '23': 'danger',
          '24': 'success',
          '25': 'danger',
          '26': 'info',
          '27': 'danger',
          '28': 'success'
        };
        return tagMap[state] || 'default';
      },

      // 订单状态文本映射
      getStateText(state) {
        const textMap = {
          '11': '待付款',
          '12': '已付款/预订成功',
          '13': '已取票',
          '14': '待审核',
          '15': '待退款',
          '20': '待付款退单结束',
          '21': '付款超时结束',
          '22': '预订成功退单结束',
          '23': '退款审核不通过结束',
          '24': '退款完成结束',
          '25': '取票超时结束',
          '26': '退票结束',
          '27': '点评超时结束',
          '28': '点评完成结束'
        };
        return textMap[state] || '未知状态';
      },


      // 1. 加载景区列表（下拉选择用）
      loadScenicList() {
        axios.get('/scenic/frontQueryAll')
                .then(res => {
                  if (res.data.code === 200) {
                    this.scenicList = res.data.data;
                  } else {
                    this.$message.error('加载景区列表失败：' + res.data.message);
                  }
                })
                .catch(err => {
                  console.error('加载景区列表出错：', err);
                  this.$message.error('网络错误，无法加载景区数据');
                });
      },

      // 2. 加载所有门票列表
      loadTicketList() {
        // 方案1：调用已有的分页查询接口（传默认分页参数）
        axios.post('/ticket/queryByPage', {
          pageNo: 1,    // 默认查第1页
          pageSize: 100, // 查足够多的门票（覆盖所有）
          data: {}      // 无筛选条件
        })
                .then(res => {
                  if (res.data.code === 200) {
                    // 从分页结果中提取门票列表（pageInfo.list）
                    this.ticketList = res.data.data.list;
                  } else {
                    this.$message.error('加载门票列表失败：' + res.data.message);
                  }
                })
                .catch(err => {
                  console.error('加载门票列表出错：', err);
                  this.$message.error('网络错误，无法加载门票数据');
                });
      },

      // 3. 加载订单列表
      loadData() {
        const searchParams = {};
        if (this.searchForm.orderId) searchParams.orderId = this.searchForm.orderId;
        if (this.searchForm.orderNo) searchParams.orderNo = this.searchForm.orderNo;
        if (this.searchForm.orderQpname) searchParams.orderQpname = this.searchForm.orderQpname;
        if (this.searchForm.orderYwrq) searchParams.orderYwrq = formatDate(this.searchForm.orderYwrq);
        if (this.searchForm.orderPtype) searchParams.orderPtype = this.searchForm.orderPtype;
        if (this.searchForm.orderState) searchParams.orderState = this.searchForm.orderState;
        if (this.searchForm.scenicName) searchParams.scenicName = this.searchForm.scenicName;
        if (this.searchForm.ticketName) searchParams.ticketName = this.searchForm.ticketName;

        axios.post('/order/queryByPage', {
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          data: searchParams
        })
                .then(res => {
                  if (res.data.code === 200) {
                    this.tableData = res.data.data.list;
                    this.total = res.data.data.total;
                  } else {
                    this.$message.error('加载失败：' + res.data.message);
                  }
                })
                .catch(err => {
                  console.error(err);
                  this.$message.error('网络错误或接口异常');
                });
      },

      // 分页相关方法
      handleSizeChange(val) {
        this.pageSize = val;
        this.loadData();
      },
      handleCurrentChange(val) {
        this.currentPage = val;
        this.loadData();
      },
      search() {
        this.currentPage = 1;
        this.loadData();
      },


      // 重置表单
      resetForm(formRef) {
        const ref = this.$refs[formRef];
        if (ref) {
          ref.clearValidate();
          ref.resetFields();
          // 重置表单默认值
          this.form = this.isEdit
                  ? { ...this.form, orderYwrq: new Date(this.form.orderYwrq || '') }
                  : {
                    orderId: '',
                    orderNo: generateOrderNo(),
                    orderYwrq: '',
                    orderPtype: '',
                    orderTprice: 0,
                    orderCount: 0,
                    orderQpname: '',
                    orderQprsj: '',
                    orderState: '',
                    visitors: [],
                    orderItems: [{
                      itemId: null,
                      scenicId: null,
                      ticketId: null,
                      itemPrice: null,
                      itemCount: 1,
                      itemTotalPrice: null
                    }]
                  };
        }
      },

      // 新增订单
      handleAdd() {
        this.dialogFormVisible = true;
        this.title = '添加订单';
        this.isEdit = false;
        // 从LocalStorage获取登录用户的visitorId（需确保登录时存储）
        const loginVisitor = JSON.parse(localStorage.getItem('loginVisitor'));
        const visitorId = loginVisitor ? loginVisitor.visitorId : 1; // 1为默认测试值

        this.form = {
          orderId: '',
          visitorId: visitorId, // 赋值visitorId
          orderNo: generateOrderNo(), // 使用统一的订单号生成方法
          orderYwrq: '',
          orderPtype: '',
          orderTprice: 0,
          orderCount: 0,
          orderQpname: '',
          orderQprsj: '',
          orderState: '11', // 默认待付款
          visitors: [],
          orderItems: [{
            itemId: null,
            scenicId: null,
            ticketId: null,
            itemPrice: null,
            itemCount: 1,
            itemTotalPrice: null
          }]
        };
        // 加载所有门票
        this.loadTicketList();
        this.$nextTick(() => this.$refs.form.clearValidate());
      },

      // 编辑订单
      handleEdit(index, row) {
        this.dialogFormVisible = true;
        this.title = '编辑订单';
        this.isEdit = true;
        this.form = JSON.parse(JSON.stringify(row));
        if (!this.form.visitors) {
          this.form.visitors = [];
        }
        // 处理订单项：从嵌套对象中提取scenicId和ticketId
        if (row.orderItemList && row.orderItemList.length > 0) {
          this.form.orderItems = row.orderItemList.map(item => ({
            ...item,
            // 从ticket对象中提取ticketId和scenicId
            ticketId: item.ticket?.ticketId || null,
            scenicId: item.ticket?.scenic?.scenicId || item.ticket?.scenicId || null,
            // 确保单价和数量字段映射正确（根据实际后端字段调整）
            itemPrice: item.unitPrice || item.itemPrice,
            itemCount: item.quantity || item.itemCount,
            itemTotalPrice: (item.unitPrice && item.quantity) ? (item.unitPrice * item.quantity).toFixed(2) : null
          }));
        } else if (!this.form.orderItems || this.form.orderItems.length === 0) {
          this.form.orderItems = [{
            itemId: null,
            scenicId: null,
            ticketId: null,
            itemPrice: null,
            itemCount: 1,
            itemTotalPrice: null
          }];
        }
        // 确保订单状态被正确设置
        if (row.orderState) {
          this.form.orderState = row.orderState;
        }
        if (row.orderYwrq) this.form.orderYwrq = new Date(row.orderYwrq);
        this.loadTicketList(); // 确保门票列表已加载
        this.loadScenicList(); // 确保景区列表已加载

        // 等待数据加载完成后设置下拉框的默认值
        this.$nextTick(() => {
          setTimeout(() => {
            this.$refs.form.clearValidate();
          }, 100);
        });
      },

      // 提交表单（新增/编辑）
      submitForm(formRef) {
        // 验证订单项（保留原有）
        if (!this.validateOrderItems()) {
          return;
        }

        this.$refs[formRef].validate(valid => {
          if (valid) {
            // 区分新增和编辑的数据结构
            let submitData;

            if (this.isEdit) {
              // 编辑订单：只提交Order对象（不包含orderItemList）
              submitData = {
                // 订单主表字段（从form中提取）
                orderId: this.form.orderId,
                visitorId: this.form.visitorId,
                orderNo: this.form.orderNo,
                orderYwrq: this.form.orderYwrq ? formatDate(this.form.orderYwrq) : '',
                orderPtype: this.form.orderPtype,
                orderTprice: this.form.orderTprice,
                orderCount: this.form.orderCount,
                orderQpname: this.form.orderQpname,
                orderQprsj: this.form.orderQprsj,
                orderState: this.form.orderState
              };
            } else {
              // 新增订单：提交复合结构
              submitData = {
                order: {
                  orderId: this.form.orderId,
                  visitorId: this.form.visitorId,
                  orderNo: this.form.orderNo,
                  orderYwrq: this.form.orderYwrq ? formatDate(this.form.orderYwrq) : '',
                  orderPtype: this.form.orderPtype,
                  orderTprice: this.form.orderTprice,
                  orderCount: this.form.orderCount,
                  orderQpname: this.form.orderQpname,
                  orderQprsj: this.form.orderQprsj,
                  orderState: this.form.orderState
                },
                orderItemList: this.form.orderItems.map(item => ({
                  itemId: item.itemId,
                  ticketId: item.ticketId,
                  unitPrice: item.itemPrice,
                  quantity: item.itemCount
                }))
              };
            }

            // 2. 区分新增和编辑接口
            const apiUrl = this.isEdit ? '/order/update' : '/order/insert';

            console.log('提交数据到', apiUrl, ':', JSON.stringify(submitData, null, 2));

            axios.post(apiUrl, submitData)
                    .then(response => {
                      console.log('接口响应:', response.data);
                      if (response.data.code === 200) {
                        this.$message.success('操作成功');
                        this.loadData();
                        this.dialogFormVisible = false;
                      } else {
                        // 显示后端返回的具体错误信息
                        this.$message.error('操作失败：' + (response.data.message || '未知错误'));
                      }
                    })
                    .catch(error => {
                      console.error('网络错误：', error);
                      this.$message.error('网络异常，请检查控制台');
                    });
          } else {
            this.$message.warning('表单验证失败，请检查输入');
            return false;
          }
        });
      },

      // 验证订单项（保留，用于提交前校验）
      validateOrderItems() {
        if (!this.form.orderItems || this.form.orderItems.length === 0) {
          this.$message.error('请至少添加一个订单项');
          return false;
        }

        for (let i = 0; i < this.form.orderItems.length; i++) {
          const item = this.form.orderItems[i];
          if (!item.scenicId) {
            this.$message.error(`第 ${i+1} 个订单项请选择景区`);
            return false;
          }
          if (!item.ticketId) {
            this.$message.error(`第 ${i+1} 个订单项请选择门票`);
            return false;
          }
          if (!item.itemPrice || item.itemPrice <= 0) {
            this.$message.error(`第 ${i+1} 个订单项请输入有效的单价`);
            return false;
          }
          if (!item.itemCount || item.itemCount <= 0) {
            this.$message.error(`第 ${i+1} 个订单项请输入有效的数量`);
            return false;
          }
        }

        return true;
      },


      // 删除订单
      handleDelete(index, row) {
        this.$confirm('此操作将永久删除该订单及所有相关订单项，是否继续？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.delete(`/order/deleteById?orderId=${row.orderId}`)
                  .then(response => {
                    if (response.data.code === 200) {
                      this.$message.success('删除成功');
                      this.loadData();
                    } else {
                      this.$message.error('删除失败：' + (response.data.message || '未知错误'));
                    }
                  })
                  .catch(error => {
                    console.error(error);
                    this.$message.error('删除失败，请检查接口: ' + error.message);
                  });
        }).catch(() => {
          this.$message.info('已取消删除');
        });
      },

      // 支付相关方法（保留核心功能）
      handlePay(order) {
        this.currentPayingOrder = order;
        this.showPayment = true;
        this.createPayment(order);
      },
      handlePayInDialog() {
        this.showPayment = true;
        this.createPayment(this.form);
      },
      createPayment(order) {
        // 构造Pay类参数
        const payParam = {
          orderNo: order.orderNo,
          payPje: order.orderTprice,
          payFullmsg: "景区订单-" + order.orderNo + "-支付"
        };

        axios.post("/pay/createNative", payParam)
                .then(response => {
                  if (response.data.code === 200) {
                    this.code_url = response.data.data.code_url;
                    this.paystatus = "等待支付，请扫码";

                    // 清除旧定时器，创建3秒轮询查询支付状态
                    if (this.timer1) clearInterval(this.timer1);
                    this.timer1 = setInterval(() => {
                      this.queryPayStatus(order.orderNo);
                    }, 3000);
                  } else {
                    this.$message.error("支付创建失败: " + response.data.message);
                    this.showPayment = false;
                  }
                })
                .catch(error => {
                  this.$message.error("网络错误: " + error.message);
                  this.showPayment = false;
                });
      },
      startPaymentPolling(orderNum) {
        if (this.timer1) {
          clearInterval(this.timer1);
        }

        this.timer1 = setInterval(() => {
          this.queryPayStatus(orderNum);
        }, 3000);
      },
      queryPayStatus(orderNum) {
        axios.get(`/pay/queryStatus/${orderNum}`)
                .then(response => {
                  if (response.data.code === 200) {
                    const tradeState = response.data.data;
                    // 映射微信支付状态为中文提示
                    const statusMap = {
                      'SUCCESS': '支付成功',
                      'NOTPAY': '等待支付，请扫码',
                      'USERPAYING': '用户支付中',
                      'CLOSED': '支付已关闭',
                      'PAYERROR': '支付失败'
                    };
                    this.paystatus = statusMap[tradeState] || '未知状态';

                    // 支付成功：停止轮询、更新列表、关闭弹窗
                    if (tradeState === 'SUCCESS') {
                      clearInterval(this.timer1);
                      this.timer1 = null;
                      this.$message.success('支付成功！');
                      this.loadData(); // 刷新订单列表
                      setTimeout(() => {
                        this.showPayment = false;
                        this.code_url = '';
                        this.currentPayingOrder = null;
                      }, 1500);
                    }
                    // 支付关闭或失败：停止轮询
                    else if (['CLOSED', 'PAYERROR'].includes(tradeState)) {
                      clearInterval(this.timer1);
                      this.timer1 = null;
                    }
                  } else {
                    this.$message.error('查询支付状态失败: ' + response.data.message);
                  }
                })
                .catch(error => {
                  console.error('查询支付状态出错: ', error);
                  this.$message.error('网络错误，无法查询支付状态');
                });
      },

      // 退款相关方法（保留原有功能）
      handleRefund(order) {
        this.currentRefundingOrder = order;
        this.refundMaxAmount = parseFloat(order.orderTprice);
        this.refundForm = {
          orderNo: order.orderNo,
          refundIje: this.refundMaxAmount, // 默认全额退款
          refundReason: ''
        };
        this.showRefund = true;
      },

      // 提交退款申请
      submitRefund() {
        this.$refs.refundForm.validate(valid => {
          if (valid) {
            // 调用退款申请接口
            axios.post('/refund/insert', this.refundForm)
                    .then(response => {
                      if (response.data.code === 200) {
                        this.$message.success('退款申请提交成功');
                        this.showRefund = false;
                        // 更新订单状态为待审核(14)
                        if (this.currentRefundingOrder) {
                          this.currentRefundingOrder.orderState = '14';
                          // 同时更新后台数据
                          axios.post('/order/update', {
                            orderId: this.currentRefundingOrder.orderId,
                            orderState: '14'
                          }).catch(error => {
                            console.error('更新订单状态失败:', error);
                          });
                        }
                        this.loadData(); // 刷新订单列表
                      } else {
                        this.$message.error('退款申请提交失败: ' + (response.data.message || '未知错误'));
                      }
                    })
                    .catch(error => {
                      console.error('退款申请提交出错:', error);
                      this.$message.error('网络错误，无法提交退款申请');
                    });
          } else {
            this.$message.warning('表单验证失败，请检查输入');
            return false;
          }
        });
      },

      // 格式化日期的函数
      formatDate(date) {
        return formatDate(date);
      },
      // 格式化日期时间的函数
      formatDateTime(dateTime) {
        return formatDateTime(dateTime);
      },
    },
    // 组件销毁时清除定时器
    beforeDestroy() {
      if (this.timer1) {
        clearInterval(this.timer1);
      }
    }
  });
</script>
</body>
</html>